package backtrack;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description: 216. 组合总和 III
 * User: Li_yizYa
 * Date: 2025/6/12
 * Time: 22:23
 */
public class Solution2 {
    /**
     * 剪枝
     * @param ret
     * @param tmp
     * @param k
     * @param n
     * @param sum
     * @param cur
     */
    private void backTracking1(List<List<Integer>> ret, List<Integer> tmp, int k, int n, int sum, int cur) {
        if (tmp.size() > k || sum > n) {
            return;
        }
        // if (sum > n) {
        //     return;
        // }
        if (sum == n && tmp.size() == k) {
            ret.add(new ArrayList<>(tmp));
            return;
        }
        for (int i = cur; i <= 9 - (k - tmp.size()) + 1; i++) {
            sum += i;
            tmp.add(i);
            backTracking1(ret, tmp, k, n, sum, i + 1);
            tmp.remove(tmp.size() - 1);
            sum -=i;
        }
    }

    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> ret = new ArrayList<>();
        if (n <= 0 || k <= 0) {
            return ret;
        }
        List<Integer> tmp = new ArrayList<>();
        backTracking(ret, tmp, k, n, 0, 1);
        return ret;
    }
    /**
     * 未剪枝
     * @param k
     * @param n
     * @return
     */
    private void backTracking(List<List<Integer>> ret, List<Integer> tmp, int k, int n, int sum, int cur) {
        if (sum == n && tmp.size() == k) {
            ret.add(new ArrayList<>(tmp));
            return;
        }
        for (int i = cur; i <= 9; i++) {
            sum += i;
            tmp.add(i);
            backTracking(ret, tmp, k, n, sum, i + 1);
            tmp.remove(tmp.size() - 1);
            sum -=i;
        }
    }
}
